/*!
 * jQuery printHtml plugin v1.1
 *
 * Copyright 2012-2013 Joe Wang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function($) {
  $.printHtml = function(html, preview) {
    var pagebreak = '<div class="pagebreak"></div>';
    if ($("#printHtml").length == 0) {
      $(document.body).append('<div id="printHtml"></div>');
    }
    $(document.body).children().addClass("noprint");
    var printContent = html.replace("[pagebreak]", pagebreak);
    $("#printHtml").removeClass("noprint").html(printContent);
    if (typeof preview == "undefined" || !preview) {
      window.focus();
      window.print();
    } else {
      var pop = window.open('');
      var headHtml = document.head ? document.head.innerHTML : document.getElementsByTagName('head')[0].innerHTML;
      var popHtml = '<html><head>' +
        headHtml.replace('printHtml.css"', 'printHtml.css" media="print"') +
        '</head><body><div id="printHtml">' +
        printContent +
        '</div></body></html>';
      pop.window.document.write(popHtml);
    }
  }
})(jQuery);
